package com.cogwheel.framework.graphics;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import javax.media.opengl.GL2;

import com.cogwheel.framework.init.CPreferences;
import com.cogwheel.framework.util.CDebug;

public class CShader {
	private static final String TAG = "CWGShader";
	
	public static final int FLAG_ARG_TEXTURE = 0;
	public static final int FLAG_ARG_LIGHT_POSITION = 1;
	
	public String ShaderFile = "";
	public int shaderProgram, vertexShader, fragmentShader;
	private GL2 gl = null;
	private CPreferences Preferences;
	public int textureData;
	
	public CShader(CPreferences preferences, String shaderFile, int[] flags, GL2 gl){ ShaderFile = shaderFile; this.gl = gl; Preferences = preferences; }
	public void CWGLoadShader(){
		shaderProgram = gl.glCreateProgram();
		vertexShader = gl.glCreateShader(GL2.GL_VERTEX_SHADER);
		fragmentShader = gl.glCreateShader(GL2.GL_FRAGMENT_SHADER);
		
		String vertexShaderSource = "";
		String fragmentShaderSource = "";
		
		try{
			/*VERTEX SHADER*/
			BufferedReader reader = new BufferedReader(new FileReader(Preferences.FOLDER_SHADERS + ShaderFile + ".vert"));
			String line;
			
			while((line = reader.readLine()) != null){
				vertexShaderSource += line + '\n';
			}
			reader.close();
			
			/*FRAGMENT SHADER*/
			reader = new BufferedReader(new FileReader(Preferences.FOLDER_SHADERS + ShaderFile + ".frag"));
			line = "";
			
			while((line = reader.readLine()) != null){
				fragmentShaderSource += line + '\n';
			}
			reader.close();
			
			gl.glShaderSource(vertexShader, 1, new String[] { vertexShaderSource }, (int[]) null, 0);
			gl.glCompileShader(vertexShader);
			
			gl.glShaderSource(fragmentShader, 1, new String[] { fragmentShaderSource }, (int[]) null, 0);
			gl.glCompileShader(fragmentShader);
			
			gl.glAttachShader(shaderProgram, vertexShader);
			gl.glAttachShader(shaderProgram, fragmentShader);
			gl.glLinkProgram(shaderProgram);
			gl.glValidateProgram(shaderProgram);
			
			CDebug.info(TAG, "Shader (" + ShaderFile + ") was loaded successfully!");
			
		} catch (IOException e){ CDebug.info(TAG, "Could not load/compile shaders!"); }
	}

	public void CWGUseShader(){
		gl.glUseProgram(shaderProgram);
	}
}
